package com.AX.handler;

import com.AX.entity.GeoPoint;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(GeoPoint.class)
public class GeoPointTypeHandler extends BaseTypeHandler<GeoPoint> {

    // 将 Java 对象写入数据库（INSERT/UPDATE）
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
                                    GeoPoint parameter, JdbcType jdbcType)
            throws SQLException {
        // 按照数据库要求的顺序：纬度(lat)在前，经度(lng)在后
        String wkt = String.format("POINT(%.6f %.6f)",
                parameter.getLat(),
                parameter.getLng());
        ps.setString(i, wkt);
    }

    // 从结果集读取数据（纬度在前 => lat，经度在后 => lng）
    private GeoPoint parseWkt(String wkt) {
        System.out.println(wkt);
        if (wkt == null || !wkt.startsWith("POINT(")) {
            System.out.println("处理错误");
            return null;
        }

        // 提取坐标部分：POINT(lat lng)
        System.out.println("处理进行");
        String coordStr = wkt.substring(6, wkt.length() - 1);
        String[] coords = coordStr.split(" ");


        return new GeoPoint(
                Double.parseDouble(coords[0]), // 纬度 => lat
                Double.parseDouble(coords[1])  // 经度 => lng
        );
    }

    // 实现结果集读取方法
    @Override
    public GeoPoint getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        return parseWkt(rs.getString(columnName));
    }

    @Override
    public GeoPoint getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        return parseWkt(rs.getString(columnIndex));
    }

    @Override
    public GeoPoint getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        return parseWkt(cs.getString(columnIndex));
    }
}
